﻿using System;
using System.Threading;
using static System.Threading.Thread;
using static System.Console;

namespace Project_3
{
    /// <summary>
    /// 3.2 线程池中调用委托
    /// </summary>
    public class Unit_3_02
    {
        public static void Go()
        {
            int threadId = 0;
            RunOnThreadPool poolDelegate = Test;
            var t=new Thread(()=>Test(out threadId));
            t.Start();
            t.Join();
            WriteLine($"Thread id:{threadId}");
            IAsyncResult r = poolDelegate.BeginInvoke(out threadId, Callback, "一个委托异步调用");
            r.AsyncWaitHandle.WaitOne();

            string result = poolDelegate.EndInvoke(out threadId, r);
            WriteLine($"线程池当前运行的线程id:{CurrentThread.ManagedThreadId}");
            WriteLine(result);
            Sleep(TimeSpan.FromSeconds(2));
        }

        private delegate string RunOnThreadPool(out int threadId);

        private static void Callback(IAsyncResult ar)
        {
            WriteLine("Starting a callback...");
            WriteLine($"传递给回调函数的状态:{ar.AsyncState}");
            WriteLine($"是否是线程池托管线程：{CurrentThread.IsThreadPoolThread}");
            WriteLine($"线程池当前运行的线程id:{CurrentThread.ManagedThreadId}");
        }

        private static string Test(out int threadId)
        {
            WriteLine("Starting");
            WriteLine($"是否是线程池托管线程：{CurrentThread.IsThreadPoolThread}");
            Sleep(TimeSpan.FromSeconds(2));
            threadId = CurrentThread.ManagedThreadId;
            return $"线程池当前运行的线程id:{CurrentThread.ManagedThreadId}";
        }
    }
}
